<?php

class SQLExtJsInteract {
	
	public static $mySqlDB = null;
	
	private $table;
	private $fields;
	private $primaryKey;




public function __set ($key, $value){
    $this->vars[$key] = $value;
  }
  
  
public function __get ($key){
    return $this->vars[$key];
}
  
public function __construct($sTable, $tabFields, $sPrimaryKey){
	
	$this->table = $sTable;
	$this->fields = $tabFields;
	$this->primaryKey = ($sPrimaryKey=='') ? 'id' : $sPrimaryKey;

	
	
	if($mySqlDB == null){
		self::$mySqlDB = new MySqlClass(_HOST, _USER, _PWD, _DATABASE);
	}
}




/*
Execute l'action adéquate
@param :
@param :
@param :
@return : le resultat de l'action
*/
public function doAction($action, $filterJson, $dataJson){

    $res = '';
	switch($action){ 
		
			case 'LST':
			
				if($filterJson!=''){
					   $res = $this->selectFiltredFromJson($filterJson);
				}else{
					   $res = $this->selectAll();
				}
			  
			break;
			
			
			case 'ADD':
			       
					if($dataJson!=''){
						$res = $this->insertSQLFromJson($dataJson);
					}else{
						$res =  'Erreur : aucune données renvoyées :' .$dataJson. ' Action :' .$action ;
					}
	
	
			break;
                    
                    	case 'ADDALL':
			       
					if($dataJson!=''){
						$res = $this->insertAllSQLFromJson($dataJson);
					}else{
						$res =  'Erreur : aucune données renvoyées :' .$dataJson. ' Action :' .$action ;
					}
	
	
			break;
			
			
			case 'UPD':
	
					if($dataJson!=''){
							$res = $this->updateSQLFromJson($dataJson);
					}else{
							$res = 'Erreur : aucune données renvoyées :' .$dataJson. ' Action :' .$action ;
					}
	
			break;
			
			
			case 'DEL':
			
					if($dataJson!=''){
							$res = $this->deleteSQLFromJson($dataJson);
					}else{
							$res = 'Erreur : aucune données renvoyées :' .$dataJson. ' Action :' .$action ;
					}
	
			break;
			
			default :
					$res = 'Erreur : Action inconnu';
			break;
	
	
		}

return $res;

}


/* 
  Print * de la table
  @param : void
  @return : renvoie un string représentant un tableau json, chaque ligne de la table correspond à une occurence du tableau.
  			Aucune clause WHERE n'est envoyé
*/
private function selectAll(){
    $queryRes = self::$mySqlDB->MysqlSelect($this->table, implode(",", $this->fields));
	   
    return '{
		"success":true,
		"msg":"success",
		"data":'.json_encode($queryRes).'
	    }';
}



/*
*/
private function selectFiltredFromJson($jsonFilters){
   // global $bdd;
    
    //Supprime les filtres null envoyé par EXTjs
    $filters = array_filter(json_decode($jsonFilters), function($var){
	    return (!($var->property==null));
    });
    
    $whereClause = "WHERE";
    $filtersDone = 0;
    $nbFilters = count($filters);
    foreach($filters as $filter){ 
	
	switch(gettype($filter->value)){
	       
	    case 'integer':
		$whereClause .= " ".$filter->property."=".$filter->value;
	    break;
		
	    case 'string':
		$whereClause .= ' '.$filter->property.'="'.$filter->value.'"';
	    break;
	    
	    default:
		$whereClause .= ' '.$filter->property.'='.$filter->value.'';
	    break;
	}
	$filtersDone+=1;
	
	if (($nbFilters>1) && ($filtersDone < $nbFilters)){
	    $whereClause .= " AND";
	}
    }
    $queryRes = self::$mySqlDB->MysqlSelect($this->table, implode(",", $this->fields), $whereClause);
    return '{
		"success":true,
		"msg":"success",
		"data":'.json_encode($queryRes).'
	    }';
}



private function selectOne($id){
    $whereClause = "WHERE ". $this->primaryKey."=". $id;
    $queryRes = self::$mySqlDB->MysqlSelect($this->table, implode(",", $this->fields), $whereClause);
     return '{
	 "success":true,
	 "msg":"success",
	 "data":'.json_encode($queryRes).'
     }';
}


/*
*/
private function insertSQLFromJson($dataJson){
	   
  	   $tableOfData = json_decode($dataJson);
  	   $valueRow = array();
  	  	
  	   $theNewRow = $tableOfData[0];
  	  
  	   foreach($theNewRow as $field => $value){	
  	   	    $valueRow[$field] = $value;	
  	   }
  	   		
   	  	
	   self::$mySqlDB->MysqlInsert($this->table, $valueRow);
	   
	   return $this->selectOne(self::$mySqlDB->DernierID);
}


/*
*/
private function insertAllSQLFromJson($dataJson){
	   
  	   $tableOfData = json_decode($dataJson);
  	   $values = array();
  	  
  	   //contruie le tableau de valeurs du insert, une ligne par enregistrement : arrayAllRow(arrayRow1(valueField1, valueField2,…), arrayRow2(…))
  	   foreach($tableOfData as $oRow){ 
  	   		$valueRow = array();

  	   		foreach($oRow as $field => $value){	
  	   			   array_push($valueRow, $value);	
  	   		}
  	   		
  	   		array_push($values, $valueRow);
  	   	}
		
	    self::$mySqlDB->MysqlInsertAll($this->table, $this->fields , $values);
	    return '{"success":true}';
}


private function deleteSQLFromJson($dataJson){
	   
  	   $tableOfData = json_decode($dataJson);
  	
  	   $sql = "WHERE ".$this->primaryKey."=0";
  	   foreach($tableOfData as $oRow){
  	  		foreach($oRow as $field => $value){	
  	   			   if($field==$this->primaryKey)
  	   			   		$sql .= " OR ".$this->primaryKey."=".$value;

  	   		}		 
  	   }
	   self::$mySqlDB->MysqlDelete($this->table, $sql);
	   return '{"success":true}';
}



private function updateSQLFromJson($dataJson){
    
     $tableOfData = json_decode($dataJson);
     //envoie une requête par enregistrement
     foreach($tableOfData as $oRow){ 
                  
          $fieldNameAndValue = array();
          foreach($oRow as $field => $value){	
              if($field==$this->primaryKey){
                    $whichRow = " WHERE ".$this->primaryKey."=".$value;
               }else{
                    $fieldNameAndValue[$field] = $value;	
               }
          }
                                   
        self::$mySqlDB->MysqlUpdate($this->table, $fieldNameAndValue, $whichRow);
     }
     return '{"success":true}';
}



}

?>